import 'package:flutter/foundation.dart';

/// 全局配置
class GlobalConfig {
  final int maxCacheSize;
  final String? cacheDirectory;
  final bool enableDebugLogging;
  final bool enablePerformanceMonitoring;

  const GlobalConfig({
    this.maxCacheSize = 1024 * 1024 * 1024, // 1GB
    this.cacheDirectory,
    this.enableDebugLogging = kDebugMode,
    this.enablePerformanceMonitoring = true,
  });

  GlobalConfig copyWith({
    int? maxCacheSize,
    String? cacheDirectory,
    bool? enableDebugLogging,
    bool? enablePerformanceMonitoring,
  }) {
    return GlobalConfig(
      maxCacheSize: maxCacheSize ?? this.maxCacheSize,
      cacheDirectory: cacheDirectory ?? this.cacheDirectory,
      enableDebugLogging: enableDebugLogging ?? this.enableDebugLogging,
      enablePerformanceMonitoring: enablePerformanceMonitoring ?? this.enablePerformanceMonitoring,
    );
  }
}

/// 性能配置
class PerformanceConfig {
  final int maxConcurrentDownloads;
  final int maxActiveListeners;
  final int maxCacheStates;
  final Duration cleanupInterval;
  final Duration staleStateTimeout;

  const PerformanceConfig({
    this.maxConcurrentDownloads = 3,
    this.maxActiveListeners = 50,
    this.maxCacheStates = 100,
    this.cleanupInterval = const Duration(minutes: 2),
    this.staleStateTimeout = const Duration(minutes: 10),
  });

  PerformanceConfig copyWith({
    int? maxConcurrentDownloads,
    int? maxActiveListeners,
    int? maxCacheStates,
    Duration? cleanupInterval,
    Duration? staleStateTimeout,
  }) {
    return PerformanceConfig(
      maxConcurrentDownloads: maxConcurrentDownloads ?? this.maxConcurrentDownloads,
      maxActiveListeners: maxActiveListeners ?? this.maxActiveListeners,
      maxCacheStates: maxCacheStates ?? this.maxCacheStates,
      cleanupInterval: cleanupInterval ?? this.cleanupInterval,
      staleStateTimeout: staleStateTimeout ?? this.staleStateTimeout,
    );
  }
}

/// 网络配置
class NetworkConfig {
  final int connectTimeout;
  final int readTimeout;
  final int maxRetryAttempts;
  final Duration retryInterval;
  final bool enableBackgroundCaching;
  final Duration backgroundTimeout;

  const NetworkConfig({
    this.connectTimeout = 30000, // 30秒
    this.readTimeout = 60000, // 60秒
    this.maxRetryAttempts = 3,
    this.retryInterval = const Duration(seconds: 30),
    this.enableBackgroundCaching = true,
    this.backgroundTimeout = const Duration(minutes: 5),
  });

  NetworkConfig copyWith({
    int? connectTimeout,
    int? readTimeout,
    int? maxRetryAttempts,
    Duration? retryInterval,
    bool? enableBackgroundCaching,
    Duration? backgroundTimeout,
  }) {
    return NetworkConfig(
      connectTimeout: connectTimeout ?? this.connectTimeout,
      readTimeout: readTimeout ?? this.readTimeout,
      maxRetryAttempts: maxRetryAttempts ?? this.maxRetryAttempts,
      retryInterval: retryInterval ?? this.retryInterval,
      enableBackgroundCaching: enableBackgroundCaching ?? this.enableBackgroundCaching,
      backgroundTimeout: backgroundTimeout ?? this.backgroundTimeout,
    );
  }
}

/// 安全配置
class SecurityConfig {
  final bool enableHttps;
  final bool validateCertificates;
  final List<String> allowedDomains;
  final List<String> blockedDomains;

  const SecurityConfig({
    this.enableHttps = true,
    this.validateCertificates = true,
    this.allowedDomains = const [],
    this.blockedDomains = const [],
  });

  SecurityConfig copyWith({
    bool? enableHttps,
    bool? validateCertificates,
    List<String>? allowedDomains,
    List<String>? blockedDomains,
  }) {
    return SecurityConfig(
      enableHttps: enableHttps ?? this.enableHttps,
      validateCertificates: validateCertificates ?? this.validateCertificates,
      allowedDomains: allowedDomains ?? this.allowedDomains,
      blockedDomains: blockedDomains ?? this.blockedDomains,
    );
  }
}

/// 完整的缓存配置
class CacheConfiguration {
  final GlobalConfig global;
  final PerformanceConfig performance;
  final NetworkConfig network;
  final SecurityConfig security;

  const CacheConfiguration({
    this.global = const GlobalConfig(),
    this.performance = const PerformanceConfig(),
    this.network = const NetworkConfig(),
    this.security = const SecurityConfig(),
  });

  CacheConfiguration copyWith({
    GlobalConfig? global,
    PerformanceConfig? performance,
    NetworkConfig? network,
    SecurityConfig? security,
  }) {
    return CacheConfiguration(
      global: global ?? this.global,
      performance: performance ?? this.performance,
      network: network ?? this.network,
      security: security ?? this.security,
    );
  }

  /// 验证配置
  List<String> validate() {
    final errors = <String>[];

    // 验证全局配置
    if (global.maxCacheSize <= 0) {
      errors.add('最大缓存大小必须大于0');
    }

    // 验证性能配置
    if (performance.maxConcurrentDownloads <= 0) {
      errors.add('最大并发下载数必须大于0');
    }
    if (performance.maxActiveListeners <= 0) {
      errors.add('最大活跃监听器数必须大于0');
    }
    if (performance.maxCacheStates <= 0) {
      errors.add('最大缓存状态数必须大于0');
    }

    // 验证网络配置
    if (network.connectTimeout <= 0) {
      errors.add('连接超时时间必须大于0');
    }
    if (network.readTimeout <= 0) {
      errors.add('读取超时时间必须大于0');
    }
    if (network.maxRetryAttempts < 0) {
      errors.add('最大重试次数不能小于0');
    }

    return errors;
  }

  /// 转换为原生API配置
  Map<String, dynamic> toNativeConfig() {
    return {
      'maxCacheSize': global.maxCacheSize,
      'cacheDirectory': global.cacheDirectory,
      'maxConcurrentDownloads': performance.maxConcurrentDownloads,
      'connectTimeout': network.connectTimeout,
      'readTimeout': network.readTimeout,
    };
  }
}

/// 配置管理器
class CacheConfigurationManager {
  static CacheConfigurationManager? _instance;
  static CacheConfigurationManager get instance => _instance ??= CacheConfigurationManager._();

  CacheConfigurationManager._();

  CacheConfiguration _configuration = const CacheConfiguration();
  bool _isInitialized = false;

  /// 初始化配置
  void initialize(CacheConfiguration configuration) {
    if (_isInitialized) {
      debugPrint('CacheConfigurationManager: 配置已初始化，跳过重复初始化');
      return;
    }

    // 验证配置
    final errors = configuration.validate();
    if (errors.isNotEmpty) {
      throw ArgumentError('配置验证失败: ${errors.join(', ')}');
    }

    _configuration = configuration;
    _isInitialized = true;
    debugPrint('CacheConfigurationManager: 配置初始化完成');
  }

  /// 获取当前配置
  CacheConfiguration get configuration {
    if (!_isInitialized) {
      throw StateError('配置管理器未初始化，请先调用initialize()');
    }
    return _configuration;
  }

  /// 更新配置
  void updateConfiguration(CacheConfiguration configuration) {
    final errors = configuration.validate();
    if (errors.isNotEmpty) {
      throw ArgumentError('配置验证失败: ${errors.join(', ')}');
    }

    _configuration = configuration;
    debugPrint('CacheConfigurationManager: 配置已更新');
  }

  /// 重置为默认配置
  void resetToDefault() {
    _configuration = const CacheConfiguration();
    debugPrint('CacheConfigurationManager: 配置已重置为默认值');
  }

  /// 获取配置摘要
  Map<String, dynamic> getConfigurationSummary() {
    return {
      'global': {
        'maxCacheSize': _configuration.global.maxCacheSize,
        'enableDebugLogging': _configuration.global.enableDebugLogging,
        'enablePerformanceMonitoring': _configuration.global.enablePerformanceMonitoring,
      },
      'performance': {
        'maxConcurrentDownloads': _configuration.performance.maxConcurrentDownloads,
        'maxActiveListeners': _configuration.performance.maxActiveListeners,
        'maxCacheStates': _configuration.performance.maxCacheStates,
      },
      'network': {
        'connectTimeout': _configuration.network.connectTimeout,
        'readTimeout': _configuration.network.readTimeout,
        'maxRetryAttempts': _configuration.network.maxRetryAttempts,
        'enableBackgroundCaching': _configuration.network.enableBackgroundCaching,
      },
      'security': {
        'enableHttps': _configuration.security.enableHttps,
        'validateCertificates': _configuration.security.validateCertificates,
        'allowedDomainsCount': _configuration.security.allowedDomains.length,
        'blockedDomainsCount': _configuration.security.blockedDomains.length,
      },
    };
  }
}
